package com.promis.util;

import android.content.Context;
import android.os.Environment;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FileUtils {

	public static File getImgFile(Context context, String fileName) {
		File dir = getCacheFilesDir(context, Environment.DIRECTORY_PICTURES);
		return new File(dir, fileName);
	}

	public static File getXmlFile(Context context, String fileName) {
		File dir = getCacheFilesDir(context, Environment.DIRECTORY_DOCUMENTS);
		return new File(dir, fileName);
	}

	public static File getDownloadFile(Context context, String fileName) {
		File dir = getCacheFilesDir(context, Environment.DIRECTORY_DOWNLOADS);
		return new File(dir, fileName);
	}

	public static File getVideoFile(Context context, String fileName) {
		File dir = getCacheFilesDir(context, Environment.DIRECTORY_MOVIES);
		return new File(dir, fileName);
	}

	public static File getCacheFilesDir(Context context, String cacheName) {
		File cacheDir = context.getExternalCacheDir();
		if (cacheDir != null) {
			File result = new File(cacheDir, cacheName);
			if (!result.mkdirs() && (!result.exists() || !result.isDirectory())) {
				// File wasn't able to create a directory, or the result exists but not a directory
				return null;
			}
			return result;
		}
		return null;
	}

	public static String[] getAssetsFileNames(Context context, String assetsPath) {
		try {
			return context.getAssets().list(assetsPath);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String getFileSize(File file) {
		if (!file.exists()) {
			return "0 MB";
		} else {
			long size = file.length();
			return (size / 1024f) / 1024f + "MB";
		}
	}

	public static byte[] readFileToBytes(String filePath) {
		return readFileToBytes(new File(filePath));
	}

	public static byte[] readFileToBytes(File file) {
		int byte_size = 1024;
		byte[] b = new byte[byte_size];
		try {
			FileInputStream fileInputStream = new FileInputStream(file);
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream(
					byte_size);
			for (int length; (length = fileInputStream.read(b)) != -1;) {
				outputStream.write(b, 0, length);
			}
			fileInputStream.close();
			outputStream.close();
			return outputStream.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
